package com.zj.services;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zj.pojo.Apple;
import com.zj.pojo.Result;
import com.zj.tools.MyObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

@Service
public class FarmerService implements BaseService{

    private static Logger log= LoggerFactory.getLogger(FarmerService.class);

    private final RestTemplate template;

    private String APPLE_HOST_URL="http://localhost:10010/crud";

    public FarmerService(RestTemplateBuilder templateBuilder) {
        this.template = templateBuilder.build();
    }


    @Override
    public int insertApples(Apple apple) {
        ResponseEntity<Result> resultResponseEntity = template.postForEntity(APPLE_HOST_URL + "/apple/add", apple, Result.class);
        Integer res = MyObjectMapper.myMapper.convertValue(resultResponseEntity.getBody().getData(), Integer.class);
        return res;
    }

    @Override
    public Apple getAppleById(int id) {
        Result result = template.getForObject(APPLE_HOST_URL + "/apple/{id}", Result.class, 1);
        log.info("getAppleById:----"+result.toString());
//        Apple apple = MyObjectMapper.INSTANCE.toApple((Map<String, Object>) result.getData());
        Apple apple = MyObjectMapper.myMapper.convertValue(result.getData(), Apple.class);
        return apple;
    }

    @Override
    public List<Apple> updateAppleById(int id, Apple apple) {
        template.put(APPLE_HOST_URL + "/apple/{id}", apple,id);

        return getApppool();
    }

    @Override
    public List<Apple> getApppool() {
        Result result = template.getForObject(APPLE_HOST_URL + "/apple/all", Result.class);
        log.info("getAppleAll:----"+result.toString());
//        List<Apple> apples = MyObjectMapper.INSTANCE.toAppleList((List<Map<String, Object>>) result.getData());
        List<Apple> apples = MyObjectMapper.myMapper.convertValue(result.getData(), new TypeReference<List<Apple>>() {
        });
        return apples;
    }

    @Override
    public List<Apple> deleteApple(int id) {
        template.delete(APPLE_HOST_URL + "/apple/{id}", id);
        return getApppool();
    }
}
